package com.jnxx.task.service.impl;

import com.jnxx.basic.service.impl.BaseServiceImpl;
import com.jnxx.basic.util.GetStaffRequestUtil;
import com.jnxx.okr.domain.Okr;
import com.jnxx.okr.mapper.OkrMapper;
import com.jnxx.task.controller.WechatController;
import com.jnxx.task.domain.*;
import com.jnxx.task.domain.Module;
import com.jnxx.task.mapper.*;
import com.jnxx.task.service.ITaskService;
import com.jnxx.task.taskRemind.MessageProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Slf4j
@Service
public class TaskServiceImpl extends BaseServiceImpl<Task> implements ITaskService {

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private OkrprojectMapper okrprojectMapper;

    @Autowired
    private OkrcardMapper okrcardMapper;

    @Autowired
    private ModuleMapper moduleMapper;

    @Autowired
    private TaskandstaffMapper taskandstaffMapper;

    @Autowired
    private OkrStaffMapper staffMapper;

    @Autowired
    private OkrMapper okrMapper;

    @Autowired
    private MessageProducer messageProducer;

    @Autowired
    private WechatController wechatController;

    /**
     *  按不同任务级别分类给前端
     * @param task
     * @return
     */
    @Override
    public HashMap<String, List<Task>> getStaffTaskById(Task task) {
        List<Task> taskList = taskMapper.getStaffTaskById(task);

        List<Task> mostHight = taskList.stream().filter(c -> "最高".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> Hight = taskList.stream().filter(c -> "较高".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> common = taskList.stream().filter(c -> "普通".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> low = taskList.stream().filter(c -> "较低".equals(c.getTaskLevel())).collect(Collectors.toList());

        HashMap<String, List<Task>> stringListHashMap = new HashMap<>();
        if (mostHight.size() != 0){
            stringListHashMap.put("mostHight", mostHight);
        }
        if (Hight.size() != 0){
            stringListHashMap.put("Hight", Hight);
        }
        if (common.size() != 0){
            stringListHashMap.put("common", common);
        }
        if (low.size() != 0){
            stringListHashMap.put("low", low);
        }
        return stringListHashMap;
    }

    /**
     * 查询当前登录人的延期任务
     * @param task
     * @return
     */
    @Override
    public HashMap<String, List<Task>> selectDelayTask(Task task) {

        List<Task> taskList = taskMapper.selectDelayTask(task);
        if (taskList.size() == 0){
            return null;
        }

        List<Task> mostHight = taskList.stream().filter(c -> "最高".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> Hight = taskList.stream().filter(c -> "较高".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> common = taskList.stream().filter(c -> "普通".equals(c.getTaskLevel())).collect(Collectors.toList());
        List<Task> low = taskList.stream().filter(c -> "较低".equals(c.getTaskLevel())).collect(Collectors.toList());

        HashMap<String, List<Task>> stringListHashMap = new HashMap<>();
        if (mostHight.size() != 0){
            stringListHashMap.put("mostHight", mostHight);
        }
        if (Hight.size() != 0){
            stringListHashMap.put("Hight", Hight);
        }
        if (common.size() != 0){
            stringListHashMap.put("common", common);
        }
        if (low.size() != 0){
            stringListHashMap.put("low", low);
        }
        return stringListHashMap;
    }

    // 点击完成任务
    @Override
    public void changeStates(Task task) {

        taskMapper.changeStates(task);

        HashMap<String,String> map = new HashMap<>();
        // 通知创建人
        OkrStaff one = staffMapper.findOne(task.getCreatStaffId());
        map.put("touser", one.getUserId());
        map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您发布的任务： "+ task.getTaskName() + "，已完成</div><div class=\"highlight\"></div>");
        wechatController.sendMessage(map);
    }

    /**
     * 负责人点击接收任务
     * @param id
     */
    @Override
    public void updatSureState(Long id) {
        taskMapper.updatSureState(id);
        Task task = taskMapper.findOne(id);
        HashMap<String,String> map = new HashMap<>();
        // 通知创建人
        OkrStaff one = staffMapper.findOne(task.getCreatStaffId());
        map.put("touser", one.getUserId());
        map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您发布的任务已被接收</div><div class=\"highlight\">任务名称："+ task.getTaskName() +"</div>");
        wechatController.sendMessage(map);
    }

    /**
     * 根据任务id，更新评价星级
     * @param id
     * @param myStart
     * @param leaderStart
     */
    @Override
    public void successEvaluation(Long id, Long myStart, Long leaderStart) {
        taskMapper.successEvaluation(id, myStart, leaderStart);
    }

    /**
     * 查询负责人没有接收的任务
     * @return
     */
    @Override
    public List<Task> findByNotReceiveTask() {
        return taskMapper.findByNotReceiveTask();
    }

    /**
     * 一键提醒完成任务
     * @param id
     */
    @Override
    public void reminderTask(Long id) {
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        Task task = taskMapper.selectTaskAndStaffList(id);
        List<OkrStaff> staffList = task.getStaffList();
        if (staffList.size() > 0){
            // 去掉创建人
            staffList = staffList.stream().filter(e-> !Objects.equals(e.getId(), staff.getId())).collect(Collectors.toList());

            String collect = staffList.stream().map(OkrStaff::getUserId).collect(Collectors.joining("|"));
            HashMap<String,String> map = new HashMap<>();
            // 通知所有人
            map.put("touser", collect);
            map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">"+ staff.getName() + "提醒您，任务：" + task.getTaskName() + "，还未完成</div><div class=\"highlight\"></div>");
            wechatController.sendMessage(map);
        }

    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void del(Long id) {
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        Task task = super.findOne(id);
        log.info("{}删除了名为：{}，的任务", staff.getName(), task.getTaskName());
        taskandstaffMapper.delByTaskId(task.getId());
        commentMapper.delCommonByTaskId(id);

        super.del(id);
    }

    @Override
    public void batchDel(List<Long> ids) {
        for (Long id : ids) {
            commentMapper.delCommonByTaskId(id);
        }
        super.batchDel(ids);
    }

    // 修改任务
    @Override
    public void update(Task task) {
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        Long id = task.getId();
        OkrStaff leader = task.getLeader();
        Long leaderId = leader.getId();
        task.setStaffId(leaderId);
        if (Objects.equals(task.getTaskProgress(), "100")){
            task.setStates(true);
            task.setFinishTime(new Date());
        } else {
            task.setStates(false);
        }
//        Long krId = task.getOkr().getId();
        // 修改对齐id
//        task.setAlignmentId(krId);
        Okr okr = task.getOkr();
        if(okr != null){
            task.setKrId(okr.getId());
            task.setOkrId(okr.getParentId());
        }
        super.update(task);
        // 修改，先删，在加
        taskandstaffMapper.delByTaskId(id);
        Integer[] ids = task.getIds();
        if (ids.length > 0){
            addTaskAndStaff(id, ids);
        }

        String[] userIds = taskandstaffMapper.selectUserIdByTaskId(task.getId());
        // 除掉当前人
        String collect = Arrays.stream(userIds).filter(e -> !e.equals(staff.getUserId())).collect(Collectors.joining("|"));

        HashMap<String,String> map = new HashMap<>();
        // 通知所有人
        map.put("touser", collect);
        map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您的任务： "+ task.getTaskName() + "，发生变更，请前往查看</div><div class=\"highlight\"></div>");
        wechatController.sendMessage(map);

//          map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您发布的任务： "+ task.getTaskName() + "，发生变更</div><div class=\"highlight\"></div>");


    }

    // 添加
    private void addTaskAndStaff(Long id, Integer[] ids) {
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        for (Integer staffId : ids) {
            Taskandstaff taskandstaff = new Taskandstaff();
            taskandstaff.setTaskId(Math.toIntExact(id));
            taskandstaff.setStaffId(staffId);
            taskandstaff.setCreatId(Math.toIntExact(staff.getId()));
            taskandstaffMapper.add(taskandstaff);
        }
    }
    // 新增任务
    @Override
    public void add(Task task) {
        Okrproject project = null;
        OkrStaff staff = GetStaffRequestUtil.getStaff();
        // 定时任务创建 staff 为null
        if (staff != null){
            task.setCreatStaffId(staff.getId());
        }
        if (task.getOkrId() != null){
            project = okrprojectMapper.findOne(task.getProjectId());
        }
        Okrcard okrcard = null;
        if (task.getOkrId() != null){
            okrcard = okrcardMapper.findOne(task.getCardId());
        }
        Module module =null;
        if (task.getOkrId() != null){
            module = moduleMapper.findOne(task.getModuleId());
        }

        // 如果是从项目详细进行添加，需要加入项目/模块/卡片，等信息
        if (project != null && okrcard != null && module != null){
            task.setProjectDetails(project.getProjectName() + "/" + module.getModuleName()+ "/" + okrcard.getCardName());
        }
        task.setCreatTime(new Date());
        super.add(task);
        String taskLevel = task.getTaskLevel();
        int dely = 0;
        if ("最高".equals(taskLevel)){
            dely = 3600;
//            dely = 10;
        } else if ("较高".equals(taskLevel)){
            dely = 3600 * 2;
        } else if ("普通".equals(taskLevel)){
            dely = 3600 * 3;
        } else if ("较低".equals(taskLevel)){
            dely = 3600 * 5;
        }
        Boolean aBoolean = messageProducer.pushMessage(task.getId(), dely);
        if (!aBoolean){
            log.error("定时任务添加错误，任务名称：{}", task.getTaskName());
        }
        Long id = task.getId();
        Integer[] ids = task.getIds();

        if (ids.length > 0){
            Integer[] uniqueArray = Arrays.stream(ids)
                    .distinct()
                    .toArray(Integer[]::new);
            addTaskAndStaff(id, uniqueArray);
        }
    }

    @Override
    public Task findOne(Long id) {
        List<Taskandstaff> taskandstaffs = taskandstaffMapper.findByTaskId(id);
        Task task = super.findOne(id);
        if (taskandstaffs.size() >0){
            List<Integer> ids = taskandstaffs.stream().map(Taskandstaff::getStaffId).collect(Collectors.toList());

            List<OkrStaff> staffList = staffMapper.findByIds(ids);
            task.setStaffList(staffList);
        }
        OkrStaff leader = staffMapper.findOne(task.getStaffId());
        task.setLeader(leader);

        Long okrId = task.getKrId();
        Okr okr = okrMapper.findOne(okrId);
        task.setOkr(okr);

        return task;
    }
}
